

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.border.TitledBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import jsyntaxpane.DefaultSyntaxKit;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLTreePanel extends JPanel {

	private JTree tree;
	private XMLTreeModel model;
	private JSplitPane splitPane;
	private JSplitPane splitPane2;
	private JTextArea xmlText;
	private JButton saveButton;
	private JButton loadButton;
	private JEditorPane xmlEditorPane;
	private String xmlTextData = null;
	private String xmlFilePath = "google_us.xml";
	private int pathCount;
	private XMLTreeFrame nf;
	
	public XMLTreePanel() {
		setLayout(new BorderLayout());
		//nf = new newFrame();
		
		model = new XMLTreeModel();
		tree = new JTree();
		 TitledBorder leftBorder = BorderFactory.createTitledBorder("XML Viewer");
		    leftBorder.setTitleJustification(TitledBorder.LEFT);
		    TitledBorder leftBorder1 = BorderFactory.createTitledBorder("XML Editor");
		    leftBorder1.setTitleJustification(TitledBorder.LEFT);
		tree.setModel(model);
		tree.setShowsRootHandles(true);
		tree.setEditable(false);	
		xmlText = new JTextArea();
		xmlText.setVisible(true);
		xmlText.setEditable(true);
		xmlEditorPane = new JEditorPane();
		xmlEditorPane.setVisible(true);
		xmlEditorPane.setContentType("text/xml");
		saveButton = new JButton();
		saveButton.setVisible(false);
		saveButton.setText("Save Modified File");
		loadButton = new JButton();
		loadButton.setVisible(true);
		loadButton.setText("Load XML File");
		JPanel buttonPanel = new JPanel();
		buttonPanel.add(loadButton);
		buttonPanel.add(saveButton);
		
		JScrollPane xmlPane = new JScrollPane(tree);
		xmlPane.setBorder(leftBorder);
		JScrollPane textAreaPane = new JScrollPane(xmlEditorPane);
		textAreaPane.setBorder(leftBorder1);
		JScrollPane buttonPane = new JScrollPane(buttonPanel);
		
		DefaultSyntaxKit.initKit();
		splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,textAreaPane,buttonPane);
		splitPane2.setOneTouchExpandable(true);
		splitPane2.setDividerLocation(100);
		splitPane2.setPreferredSize(new Dimension(100,100));
		splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,xmlPane,textAreaPane);
		splitPane.setOneTouchExpandable(true);
		splitPane.setDividerLocation(150);
		Dimension minSize = new Dimension(150,200);
		xmlPane.setMinimumSize(minSize);
		textAreaPane.setMinimumSize(minSize);
		buttonPane.setMinimumSize(minSize);
		splitPane.setPreferredSize(new Dimension(400,200));
		
		
		//pane.setPreferredSize(new Dimension(300,400));
		
		add(splitPane, "Center");
		add(splitPane2, "South");
		
		
	/*	final JTextField text = new JTextField();
		text.setEditable(false);
		add(text, "South");*/
		
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				Object lpc = e.getPath().getLastPathComponent();
				Object lp = e.getPath();//.getParentPath();
						
				
				//Object child = model.getRoot();
				int lpcc = e.getPath().getPathCount();
				if (lpc instanceof XMLTreeNode) {
					xmlText.setText( ((XMLTreeNode)lpc).getText() );
					((XMLTreeNode) lpc).getIndex();
					
					//xmlTextData = xmlText.getText();
					xmlTextData = lpc.toString();
					pathCount = lpcc;
					System.out.println(pathCount);
					System.out.println(lp.toString());
					System.out.println(xmlTextData);
					searchString(lp.toString(),xmlTextData);
					
				}
			}

			private void searchString(String string, String xmlTextData) {
				// TODO Auto-generated method stub
				//String searchFor = ;
				//String base = "My name is gowris is shankar";
				String [] arr = string.split(" ");
				int len = arr.length;
				int result = 0;
				for(int i =0;i<len;i++)
				{
					System.out.println(arr[i]);
					/*if(arr[i].equals(xmlTextData))
					{
						//result++;
					}*/
					
				}
				System.out.println(result + " result");
				/*if (len >0)
				{
					int start = base.indexOf(searchFor);
					while(start != -1)
					{
						result++;
						start = base.indexOf(searchFor, start+len);
					}
				}
				System.out.println(result);*/
				
			}
		});
	
		final JFileChooser loadLocationChooser = new JFileChooser();
		
		loadButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				FileFilter type1 = new ExtensionFilter("XML Source",".xml");
				loadLocationChooser.addChoosableFileFilter(type1);
				 int option = loadLocationChooser.showOpenDialog(XMLTreePanel.this);
				 if(option == JFileChooser.APPROVE_OPTION){  
					 if(loadLocationChooser.getSelectedFile()!=null){  
					 File theFileToSave = loadLocationChooser.getSelectedFile();
					 
					 try {
						refreshAction(theFileToSave);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
				
					 }
				 }}
			
		});
		final JFileChooser saveLocationChooser = new JFileChooser();
		
		saveButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				FileFilter type1 = new ExtensionFilter("XML source", ".xml");
				saveLocationChooser.addChoosableFileFilter(type1);
				 int option = saveLocationChooser.showSaveDialog(XMLTreePanel.this);  
				 if(option == JFileChooser.APPROVE_OPTION){  
				 if(saveLocationChooser.getSelectedFile()!=null){  
				 File theFileToSave = saveLocationChooser.getSelectedFile();
				 try {
					saveAction1(theFileToSave);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				 }
			}
			}});
		
	}
	
	protected void saveAction1(File theFileToSave) throws IOException {
		// TODO Auto-generated method stub
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(theFileToSave),"UTF-8"));
	     // FileOutputStream fop=new FileOutputStream(f);
	      
	      out.write(xmlEditorPane.getText());
	      try {
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	      out.close();
		
	}

	protected void refreshAction(File theFileToSave) throws Exception {
		// TODO Auto-generated method stub
		//model.setDocument(document);
		saveButton.setVisible(true);
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(theFileToSave);
        model.setDocument(doc);
        System.out.println(xmlText.getText());
		StringBuilder contents = new StringBuilder();
		
		try {
	        BufferedReader in = new BufferedReader(new FileReader(theFileToSave));
	        String str = null;
	        while (( str = in.readLine()) != null){
	            contents.append(str);
	            contents.append(System.getProperty("line.separator"));
	          }              
	        //System.out.println(contents.toString());
	        xmlEditorPane.setContentType("text/xml");
	        xmlEditorPane.setText(contents.toString());
	        
	        in.close();
	    } catch (IOException e) {
	    }
		
	}
	
	protected void saveAction() throws Exception {
		// String xmlFilePath = "demo.xml";
		

	        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
	        Document doc = docBuilder.parse(xmlFilePath);

	       replaceValue(doc, xmlTextData, xmlText.getText());
	        
	        Transformer t = TransformerFactory.newInstance().newTransformer();
	        Result result = new StreamResult(new File(xmlFilePath));
	        Source source = new DOMSource(doc);
	        t.transform(source, result);
	        System.out.println(pathCount);

	}

	private void replaceValue(Document doc, String xmlTextData, String xmlTextAreaData) {
		// TODO Auto-generated method stub
		System.out.println(xmlTextAreaData);
		 NodeList nodeList = doc.getElementsByTagName(xmlTextData);
		 System.out.println("length" + nodeList.getLength());
		 Node node1 = nodeList.item(0);
	        node1.getFirstChild().setNodeValue(xmlTextAreaData);
		
	}

	/* methods that delegate to the custom model */
	public void setDocument(Document document) {
		model.setDocument(document);
	}
	public Document getDocument() {
		return model.getDocument();
	}
	
}
